﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CrawlerTBDemo
{
    public partial class Form1 : Form
    {
        private Content content;

        private JArray data = new JArray();

        private int runStatus = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webView21.EnsureCoreWebView2Async(null);
            // 设置初始 URL
            webView21.Source = new Uri("https://www.taobao.com/");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            webView21.Refresh();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            webView21.GoBack();

        }

        private async void button3_Click(object sender, EventArgs e)
        {
            if (runStatus == 0)
            {
                string sreachText = textBox1.Text;

                if (sreachText.Length == 0) 
                {

                    MessageBox.Show("请输入商品名称。");
                    return;
                }

                runStatus = 1;
                button3.Text = "停止爬取";

                data = new JArray();

                //先点击搜索
                sreach(sreachText);

                while (runStatus == 1) {
                    //有可能dom没渲染完，接收响应要时间，所以循环休眠获取结果
                    while (true)
                    {
                        await Task.Delay(500);
                        var array = await queryResult();
                        if (array != null)
                        {
                            System.Diagnostics.Debug.WriteLine($"array len:{array.Count}");
                            //添加到data集合中
                            data.Merge(array);
                            break;
                        }

                        //拿不到结果，可能是没有登录
                        bool status = await isLogin();
                        if (status == false)
                        {
                            runStatus = 0;
                            button3.Text = "开始爬取";

                            MessageBox.Show("请先登录");
                            return;

                        }

                    }

                    //更新进度
                    int n = await queryBar();
                    progressBar1.Value = n;
                    label3.Text = $"{n}%";


                    //查看是否有下一页
                    bool t = await checkNextPage();
                    if (t == false)
                    {
                        runStatus = 0;
                        button3.Text = "开始爬取";

                        //爬完了
                        break;
                    }
                }

            }
            else {
                runStatus = 0;
                button3.Text = "开始爬取";
            }
        }

        //搜索
        private async void sreach(string text) 
        {
            string search = $@"
                document.getElementById('q').value = '{text}';
                document.querySelector('.btn-search').click()
                ";
            await webView21.CoreWebView2.ExecuteScriptAsync(search);

        }

        //查询搜索结果
        private async Task<JArray> queryResult() 
        {
            JArray array = null;
            //查询搜索结果
            string script = @"
            var array = null;
            
            if(!document.querySelector('.UnusualStatus--wrap--kbi8ePx')){

                if(document.querySelector('.Title--title--jCOPvpf span')){
                    array =[];
                    var elements = document.querySelectorAll('.Content--contentInner--QVTcU0M > div');
                
                    for (const element of elements) {
                        if(!element.querySelector('.Title--title--jCOPvpf span')){
                            break;
                        }
                        var name = element.querySelector('.Title--title--jCOPvpf span').innerText;
	                    var price = element.querySelector('.Price--priceInt--ZlsSi_M').innerText + element.querySelector('.Price--priceFloat--h2RR0RK').innerText;
	                    var area = element.querySelector('.Price--procity--_7Vt3mX').innerText;
	                    var storeName = element.querySelector('.ShopInfo--TextAndPic--yH0AZfx a').innerText;
	                    var payNum = element.querySelector('.Price--realSales--FhTZc7U').innerText;
	
	                    var p = {name:name,price:price,area:area,storeName:storeName,payNum:payNum}
	                    array.push(p)
                    }
                }
               
                
                
            }else{
                array =[];
            }
            array
            ";
            string json = await webView21.CoreWebView2.ExecuteScriptAsync(script);
            if (!json.Equals("null"))
            {
                array = JArray.Parse(json);
            }
            return array;
        }

        //判断是否登录
        private async Task<bool> isLogin()
        {
            string isLoginScript = @"
            var isLogin = true;
            var iframes = document.querySelectorAll('iframe');
            for(var iframe of iframes) {
                var src = iframe.getAttribute('src')
	            var d = window.getComputedStyle(iframe).display
	            if( d === 'block' && src.indexOf('login.jhtml')!=-1){
		            isLogin = false;
		            break;
	            }
            }
            if(isLogin){
	            var divElement = document.querySelector('.login-box-warp');
	            if(divElement){
		            var computedStyle = window.getComputedStyle(divElement)
		            if(computedStyle.display == 'block'){
			            isLogin = false;
		            }
	            }
            }
            isLogin
            ";

            string loginStatus = await webView21.CoreWebView2.ExecuteScriptAsync(isLoginScript);
            return loginStatus.Equals("true");

        }

        //查看完成进度
        private async Task<int> queryBar() 
        {
            string barScript = @"
            var n = document.querySelector('.next-pagination-list .next-current span').innerText;
            var l = document.querySelector('.next-pagination-list :last-child span').innerText;
            var r = Math.floor(n/l*100);
            r
            ";
            string bar = await webView21.CoreWebView2.ExecuteScriptAsync(barScript);
            if (bar.Equals("null")) 
            {
                bar = "100";
            }

           return int.Parse(bar);
        }

        //查看是否有下一页,有就翻页
        private async Task<bool> checkNextPage()
        {
            string nextPageScript = @"
                        var nextPage = false;
                        var nextDoc = document.querySelector('.next-pagination-list .next-current').nextSibling;
                        if(nextDoc){
                            nextDoc.click();
                            nextPage = true;
                        }
                        nextPage;
                    ";
            string nextStatus = await webView21.CoreWebView2.ExecuteScriptAsync(nextPageScript);
            return nextStatus.Equals("true");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (content != null && !content.IsDisposed)
            {
                content.Dispose();
            }

            content = new Content(data);
            content.Show();
        }
    }


}
